package com.jiyinit.web.core.business.service;

import com.jiyinit.core.framework.base.paging.PagingResult;
import com.jiyinit.web.core.business.dao.TabCoreNoticeDao;
import com.jiyinit.web.core.business.dao.TabCoreUserDao;
import com.jiyinit.web.core.business.dao.TabUserNoticeDao;
import com.jiyinit.web.core.business.dto.NoticePageRequest;
import com.jiyinit.web.core.business.dto.NoticeRequest;
import com.jiyinit.web.core.business.entity.*;
import com.jiyinit.web.core.business.enums.CommonEnum;
import com.jiyinit.web.core.business.enums.SystemConstant;
import com.jiyinit.web.core.business.vo.NoticeUserVo;
import com.jiyinit.web.core.business.vo.NoticeVo;
import com.jiyinit.web.core.common.util.UserUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * Created by lr on 2017/12/27.
 */
@Service("core.noticeServiceImpl")
public class NoticeServiceImpl {

    @Resource(name="send.message")
    private ReadMessageServiceImpl readMessageService;

    @Resource(name ="core.jpushClientServiceImpl")
    private JpushClientServiceImpl jpushClientService;

    @Resource(name ="core.tabCoreNoticeDao" )
    private TabCoreNoticeDao tabCoreNoticeDao;

    @Resource(name = "core.tabUserNoticeDao")
    private TabUserNoticeDao tabUserNoticeDao;

    @Resource(name ="core.orgServiceImpl")
    private OrgServiceImpl orgService;

    @Resource(name = "core.tabCoreUserDao")
    private TabCoreUserDao tabCoreUserDao;

    public PagingResult<NoticeVo> findByPageForMobile(NoticeRequest request){
        return tabCoreNoticeDao.findByPageForMobile(request);
    }
    public PagingResult<NoticeVo> findPublishByPage(NoticeRequest request){
        return tabCoreNoticeDao.findPublishByPage(request);
    }
    public PagingResult<NoticeVo> findReceviceByPage(NoticeRequest request){
        return tabCoreNoticeDao.findReceviceByPage(request);
    }

    public List<TabCoreNoticeEntity> findTaskByIds(List<TabSendMessageEntity> list){
        return tabCoreNoticeDao.findTaskByIds(list);
    }

    public PagingResult<NoticeVo> findByPage(NoticePageRequest request){
        request.setUserId(UserUtil.getCurrentUser().getUserId());
        return tabCoreNoticeDao.findByPage(request);
    }

    public TabCoreNoticeEntity findById(Integer noticeId){
        return tabCoreNoticeDao.findById(noticeId);
    }

    public NoticeVo selectById(Integer noticeId){
        return tabCoreNoticeDao.selectById(noticeId);
    }

    public int add(NoticeRequest request){
        int num = 0;
        TabCoreNoticeEntity notice = new TabCoreNoticeEntity();
        notice.setNoticeTitle(request.getTitle());
        notice.setNoticeContent(request.getContent());
        notice.setPriority(request.getPriority());
        notice.setIsDelete(CommonEnum.IsDelete.COMMON.getCode());
        notice.setCreateId(request.getUserId());
        notice.setCreateTime(new Date());
        num =  tabCoreNoticeDao.add(notice);

        //消息推送
        HashMap<String,String> message = new HashMap<>();
        message.put("content","通知:"+ request.getTitle());
        message.put("noticeId",notice.getNoticeId().toString());

        //添加通知人员
        List<TabUserNoticeEntity> list = new ArrayList<>();
        if(request.getAlloterIds() != null) {
            String[] users = new String[request.getAlloterIds().length];
            for (int i = 0; i < request.getAlloterIds().length; i++) {
                TabUserNoticeEntity alloter = new TabUserNoticeEntity();
                alloter.setNoticeId(notice.getNoticeId());
                alloter.setUserId(request.getAlloterIds()[i]);
                alloter.setIsDelete(CommonEnum.IsDelete.COMMON.getCode());
                alloter.setCreateId(request.getUserId());
                alloter.setCreateTime(new Date());
                list.add(alloter);
                users[i] = request.getAlloterIds()[i].toString();
            }
            if(list != null && list.size()>0)  tabUserNoticeDao.add(list);
            //添加未读消息
            readMessageService.add(request.getUserId(),request.getAlloterIds(), SystemConstant.NOTICE_BOARD,notice.getNoticeId());
            jpushClientService.send(request.getChannel(),message,users);
        }
        if(request.getAlloterIds() == null) { //默认全机构
            int  j=0;
            //查询顶级机构，下的所有人员
           List<TabCoreOrgEntity> orgList =  orgService.findOrgAllMember(request.getUserId());
            List<TabCoreUserEntity> userList =  tabCoreUserDao.findUsersByOrgList(orgList);
            String[] users = new String[userList.size()];
            Integer[] usersInt = new Integer[userList.size()];
            for (TabCoreUserEntity user:userList ) {
                TabUserNoticeEntity alloter = new TabUserNoticeEntity();
                alloter.setNoticeId(notice.getNoticeId());
                alloter.setUserId(user.getUserId());
                alloter.setIsDelete(CommonEnum.IsDelete.COMMON.getCode());
                alloter.setCreateId(request.getUserId());
                alloter.setCreateTime(new Date());
                list.add(alloter);
                users[j] = user.getUserId().toString();
                usersInt[j] = user.getUserId();
                j++;
            }
            if(list != null && list.size()>0)  tabUserNoticeDao.add(list);
            //添加未读消息
            readMessageService.add(request.getUserId(),usersInt, SystemConstant.NOTICE_BOARD,notice.getNoticeId());
            jpushClientService.send(request.getChannel(),message,users);
        }

        return num;
    }

    public int update(NoticeRequest request){
        int  num = 0;
        TabCoreNoticeEntity notice = new TabCoreNoticeEntity();
        notice.setNoticeId(request.getNoticeId());
        notice.setNoticeTitle(request.getTitle());
        notice.setNoticeContent(request.getContent());
        notice.setPriority(request.getPriority());
        notice.setIsDelete(CommonEnum.IsDelete.COMMON.getCode());
        notice.setLastModifyId(request.getUserId());
        notice.setLastModifyTime(new Date());
        num =  tabCoreNoticeDao.update(notice);
        //查询所有被通知人员并推送
        List<NoticeUserVo> usersList = tabUserNoticeDao.findAlloterById(notice.getNoticeId());
        String[] users = new String[usersList.size()];
        int i=0;
        for(TabUserNoticeEntity entity : usersList){
            users[i] = entity.getUserId().toString();
            i++;
        }
        //消息推送
        HashMap<String,String> message = new HashMap<>();
        message.put("content","通知变更:"+ request.getTitle());
        message.put("noticeId",notice.getNoticeId().toString());
        jpushClientService.send(request.getChannel(),message,users);
        return num;
    }

    public NoticeVo detail(Integer id){
        return tabCoreNoticeDao.findDetailById(id);
    }

    public List<NoticeUserVo> findAlloters(Integer noticeId){
        return tabUserNoticeDao.findAlloterById(noticeId);
    }
    public int delete(Integer noticeId,Integer userId){
        int  num =  tabCoreNoticeDao.delete(noticeId,userId);
        return num;
    }

    /**
     *
     */
    public int addNotice(NoticeRequest request){
        int num = 0;
        TabCoreNoticeEntity notice = new TabCoreNoticeEntity();
        notice.setNoticeTitle(request.getTitle());
        if(request.getFileURL()==null||request.getFileURL().equals("")||request.getFileURL().equals("null")){
            notice.setNoticeContent(request.getContent());
        }else{
            notice.setNoticeContent(request.getContent()+request.getFileURL());
        }
        notice.setPriority(request.getPriority());
        notice.setIsDelete(CommonEnum.IsDelete.COMMON.getCode());
        notice.setCreateId(request.getUserId());
        notice.setCreateTime(new Date());
        notice.setPreviewNum(0);
        num =  tabCoreNoticeDao.add(notice);

        //消息推送
        HashMap<String,String> message = new HashMap<>();
        message.put("content","通知:"+ request.getTitle());
        message.put("noticeId",notice.getNoticeId().toString());

        //添加通知人员
        List<TabUserNoticeEntity> list = new ArrayList<>();
        if(request.getAlloterIds() != null) {
            String[] users = new String[request.getAlloterIds().length];
            for (int i = 0; i < request.getAlloterIds().length; i++) {
                TabUserNoticeEntity alloter = new TabUserNoticeEntity();
                alloter.setNoticeId(notice.getNoticeId());
                alloter.setUserId(request.getAlloterIds()[i]);
                alloter.setIsDelete(CommonEnum.IsDelete.COMMON.getCode());
                alloter.setCreateId(request.getUserId());
                alloter.setCreateTime(new Date());
                list.add(alloter);
                users[i] = request.getAlloterIds()[i].toString();
            }
            if(list != null && list.size()>0)  tabUserNoticeDao.add(list);
            //添加未读消息
            readMessageService.add(request.getUserId(),request.getAlloterIds(), SystemConstant.NOTICE_BOARD,notice.getNoticeId());
            jpushClientService.send(request.getChannel(),message,users);
        }
        if(request.getAlloterIds() == null) { //默认全机构
            int  j=0;
            //查询顶级机构，下的所有人员
            List<TabCoreOrgEntity> orgList =  orgService.findOrgAllMember(request.getUserId());
            List<TabCoreUserEntity> userList =  tabCoreUserDao.findUsersByOrgList(orgList);
            String[] users = new String[userList.size()];
            Integer[] usersInt = new Integer[userList.size()];
            for (TabCoreUserEntity user:userList ) {
                TabUserNoticeEntity alloter = new TabUserNoticeEntity();
                alloter.setNoticeId(notice.getNoticeId());
                alloter.setUserId(user.getUserId());
                alloter.setIsDelete(CommonEnum.IsDelete.COMMON.getCode());
                alloter.setCreateId(request.getUserId());
                alloter.setCreateTime(new Date());
                list.add(alloter);
                users[j] = user.getUserId().toString();
                usersInt[j] = user.getUserId();
                j++;
            }
            if(list != null && list.size()>0)  tabUserNoticeDao.add(list);
            //添加未读消息
            readMessageService.add(request.getUserId(),usersInt, SystemConstant.NOTICE_BOARD,notice.getNoticeId());
            jpushClientService.send(request.getChannel(),message,users);
        }

        return num;
    }

    public int updatePreviewNum(NoticeRequest noticeRequest){
        return tabCoreNoticeDao.updatePreviewNum(noticeRequest);
    }
}
